package net.qsge.common.oauth;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthServiceProvider;
import net.oauth.client.OAuthClient;
import net.oauth.client.httpclient4.HttpClient4;

/**
 * Servlet implementation class OauthSample
 */
public class OauthSample extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		OAuthClient client = new OAuthClient(new HttpClient4());

		OAuthConsumer consumer = new OAuthConsumer("", "mangaonweb.com",
				"t2opOGveWrpfeVrSZFzCh8Gk", new OAuthServiceProvider(
						"https://www.google.com/accounts/OAuthGetRequestToken",
						"https://www.google.com/accounts/OAuthAuthorizeToken",
						"https://www.google.com/accounts/OAuthGetAccessToken"));
		OAuthAccessor accessor = new OAuthAccessor(consumer);
		Map<String, String> parameters = new HashMap<String, String>();
		StringBuffer url = request.getRequestURL();
		
		url.replace(url.lastIndexOf("/"), url.length(), "").append("/callback");
		parameters.put(OAuth.OAUTH_CALLBACK, url.toString());
		parameters.put("scope", "https://www.google.com/m8/feeds/");
		try {
			client.getRequestToken(accessor, "GET", parameters.entrySet());
		} catch (OAuthException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	    Map<String, String> result = new HashMap<String, String>();
	    result.put("requestToken", accessor.requestToken);
	    result.put("tokenSecret", accessor.tokenSecret);

	    String authURL = "https://www.google.com/accounts/OAuthAuthorizeToken" + "?oauth_token=" + accessor.requestToken;

	    request.getSession().setAttribute("accessor", result);

	    response.sendRedirect(authURL);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
